package com.basic.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.basic.backend.manager.CosManager;
import com.basic.backend.mapper.ArticleVideosMapper;
import com.basic.backend.model.dto.Images.ImageAnalysisDTO;
import com.basic.backend.model.dto.articles.ArticleQueryRequest;
import com.basic.backend.model.entity.ArticleVideos;
import com.basic.backend.model.vo.VideoVO;
import com.basic.backend.service.ArticleVideosService;
import com.basic.backend.service.ArticlesService;
import com.basic.backend.service.UserService;
import com.basic.backend.utils.VideoProcessor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author ASUS
* @description 针对表【article_videos(视频类文章数据表（含视频元数据）)】的数据库操作Service实现
* @createDate 2025-03-26 17:29:35
*/
@Service
public class ArticleVideosServiceImpl extends ServiceImpl<ArticleVideosMapper, ArticleVideos>
    implements ArticleVideosService {

    @Resource
    private  CosManager cosManager;

    @Resource
    private ArticlesService articleService;

    @Resource
    private UserService userService;

    @Resource
    private MessageProducer messageProducer;

    @Resource
    private ArticleVideosMapper articleVideosMapper;

    public void VideoProcessService(CosManager cosManager, ArticlesService articleService) {
        this.cosManager = cosManager;
        this.articleService = articleService;
    }

    /**
     * 异步处理视频上传和切片
     *
     * @param videoFile 上传的视频文件
     * @param title     文章标题
     * @param content   文章内容
     * @param userId
     * @return
     */

    public boolean processVideoArticle(MultipartFile videoFile, String title, String content, Long userId) {
        ArticleVideos article = new ArticleVideos();
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(userId);
        article.setVideoUrl(" ");
        article.setImages(" ");
        this.save(article);
        String articleId = article.getArticleId().toString();
        // 创建临时目录
        File tempDir = null;
        try {
            tempDir = Files.createTempDirectory("video_process").toFile();

            // 1. 保存上传视频到临时文件
            File uploadedVideo = new File(tempDir, "video.mp4");
            videoFile.transferTo(uploadedVideo);

            // 2. 视频切片生成图片
            List<File> frameFiles = VideoProcessor.extractFrames(
                    uploadedVideo, tempDir, 5); // 每5秒截一帧

            // 3. 构建COS路径
            String cosBasePath = "articles/" + articleId + "/";

            // 4. 上传视频文件
            String videoKey = cosBasePath + "video.mp4";
            cosManager.putObject(videoKey, uploadedVideo);
            String videoUrl = buildPureUrl(videoKey);

            // 5. 上传图片文件
            List<String> imageUrls = new ArrayList<>();
            for (int i = 0; i < frameFiles.size(); i++) {
                File frameFile = frameFiles.get(i);
                String imageKey = cosBasePath + String.format("___%d.png", i+1);
                cosManager.putObject(imageKey, frameFile);
                imageUrls.add(buildPureUrl(imageKey));
            }

            // 6. 保存文章信息
            article.setVideoUrl(videoUrl);
            article.setImages(String.join(",", imageUrls));
            this.updateById(article);
            ImageAnalysisDTO analysisDTO = new ImageAnalysisDTO();
            analysisDTO.setArticleId(article.getArticleId());
            analysisDTO.setImageUrls(article.getImages());
            analysisDTO.setTitle(title);
            analysisDTO.setContent(content);
            analysisDTO.setPublishTime(LocalDateTime.now().toString());
            // 4. 发送分析任务到消息队列
            messageProducer.sendImageAnalysisTask(analysisDTO);
            return true;
        } catch (Exception e) {
            log.error("视频处理失败: {}", e);
            this.removeById(article.getArticleId());
            // 清理已上传文件
            cleanupCosFiles(articleId);
            throw new RuntimeException("视频处理失败", e);
        } finally {
            // 清理临时文件
            if (tempDir != null) {
                deleteDirectory(tempDir);
                return false;
            }
        }
    }

    private String buildPureUrl(String key) {
        return String.format("https://%s.cos.%s.myqcloud.com/%s",
                cosManager.getBucketName(),
                cosManager.getRegion(),
                key.replace(" ", "%20")); // 处理空格编码
    }

    private void cleanupCosFiles(String articleId) {
        try {
            String folder = "articles/" + articleId + "/";
            cosManager.deleteObject(folder + "video.mp4");

            // 遍历删除图片（实际生产环境建议使用COS批量删除）
            /*for (int i = 1; ; i++) {
                String key = folder + String.format("___%03d.png", i);
                if (!cosManager.objectExists(key)) break;
                cosManager.deleteObject(key);
            }*/
        } catch (Exception e) {
            /*log.warn("COS文件清理失败: {}", e.getMessage());*/
        }
    }

    private void deleteDirectory(File dir) {
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteDirectory(file);
                } else {
                    file.delete();
                }
            }
        }
        dir.delete();
    }

    @Override
    public Page<VideoVO> getArticleImagesPage(ArticleQueryRequest request, HttpServletRequest httpRequest) {
        // 1. 构建统一查询条件
        QueryWrapper<ArticleVideos> wrapper = new QueryWrapper<>();

        // 精确查询
        if (request.getArticleId() != null) {
            wrapper.eq("articleId", request.getArticleId());
        }
        if (request.getUserId() != null) {
            wrapper.eq("userId", request.getUserId());
        }

        // 模糊查询
        if (StringUtils.isNotBlank(request.getTitle())) {
            wrapper.like("title", request.getTitle());
        }

        // 状态查询
        if (request.getStatusList() != null && !request.getStatusList().isEmpty()) {
            wrapper.in("status", request.getStatusList());
        }

        // 时间范围
        if (request.getCreateTimeRange() != null) {
            Date start = request.getCreateTimeRange().getStartTime();
            Date end = request.getCreateTimeRange().getEndTime();
            if (start != null && end != null) {
                wrapper.between("createdAt", start, end);
            }
        }

        // 处理排序
        handleSort(wrapper, request.getSortField(), request.getSortOrder());

        // 2. 执行单表分页查询
        Page<ArticleVideos> page = new Page<>(request.getCurrent(), request.getSize());
        Page<ArticleVideos> resultPage = articleVideosMapper.selectPage(page, wrapper);

        // 3. 转换为VO（直接处理图片数据）
        return (Page<VideoVO>) resultPage.convert(this::convertToVO);
    }

    // 处理排序逻辑
    private void handleSort(QueryWrapper<ArticleVideos> wrapper, String sortField, String sortOrder) {
        Set<String> allowedFields = new HashSet<>(Arrays.asList("title", "createdAt", "updatedAt"));

        if (StringUtils.isNotBlank(sortField) && allowedFields.contains(sortField)) {
            boolean isAsc = (sortOrder != null && sortOrder.equalsIgnoreCase("asc"));
            wrapper.orderBy(true, isAsc, sortField);
        } else {
            // 默认按创建时间降序
            wrapper.orderByDesc("createdAt");
        }
    }

    // 实体转VO（包含图片处理）
    private VideoVO convertToVO(ArticleVideos entity) {
        VideoVO vo = new VideoVO();
        BeanUtils.copyProperties(entity, vo);

        // 设置作者信息
        vo.setAuthor(userService.getUserVO(entity.getUserId()));

        // 处理图片数据
        vo.setImages(parseImages(entity.getImages()));

        return vo;
    }

    // 解析图片字符串
    private List<String> parseImages(String images) {
        if (StringUtils.isBlank(images)) {
            return Collections.emptyList();
        }
        return Arrays.stream(images.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
    }


    @Async("videoTaskExecutor")
    public void updateVideoArticle(MultipartFile videoFile, String title, String content, Long articleId) {
        // 获取现有文章
        ArticleVideos existingArticle = this.getById(articleId);
        if (existingArticle == null) {
            throw new RuntimeException("文章不存在");
        }

        // 保留原始数据用于回滚
        String originalVideoUrl = existingArticle.getVideoUrl();
        String originalImages = existingArticle.getImages();
        File tempDir = null;
        boolean videoUpdated = false;

        try {
            // 仅当有新视频上传时处理视频文件
            if (videoFile != null && !videoFile.isEmpty()) {
                videoUpdated = true;
                tempDir = Files.createTempDirectory("video_update").toFile();

                // 1. 保存上传视频到临时文件
                File uploadedVideo = new File(tempDir, "video.mp4");
                videoFile.transferTo(uploadedVideo);

                // 2. 视频切片生成图片（与创建逻辑一致）
                List<File> frameFiles = VideoProcessor.extractFrames(uploadedVideo, tempDir, 5);

                // 3. 构建COS路径
                String cosBasePath = "articles/" + articleId + "/";

                // 4. 上传视频文件（覆盖原有文件）
                String videoKey = cosBasePath + "video.mp4";
                cosManager.putObject(videoKey, uploadedVideo);
                existingArticle.setVideoUrl(buildPureUrl(videoKey));

                // 5. 上传图片文件（覆盖原有文件）
                List<String> newImageUrls = new ArrayList<>();
                for (int i = 0; i < frameFiles.size(); i++) {
                    File frameFile = frameFiles.get(i);
                    String imageKey = cosBasePath + String.format("___%d.png", i+1);
                    cosManager.putObject(imageKey, frameFile);
                    newImageUrls.add(buildPureUrl(imageKey));
                }
                existingArticle.setImages(String.join(",", newImageUrls));
            }

            // 6. 更新文章信息（仅更新有变化的字段）
            boolean needsUpdate = false;
            if (title != null && !title.equals(existingArticle.getTitle())) {
                existingArticle.setTitle(title);
                needsUpdate = true;
            }
            if (content != null && !content.equals(existingArticle.getContent())) {
                existingArticle.setContent(content);
                needsUpdate = true;
            }
            if (videoUpdated) {
                needsUpdate = true;
            }

            if (needsUpdate) {
                this.updateById(existingArticle);
            }

            // 7. 发送分析任务（仅当有修改时）

            ImageAnalysisDTO analysisDTO = new ImageAnalysisDTO();
            analysisDTO.setArticleId(articleId);
            analysisDTO.setImageUrls(existingArticle.getImages());
            analysisDTO.setTitle(existingArticle.getTitle());
            analysisDTO.setContent(existingArticle.getContent());
            analysisDTO.setPublishTime(LocalDateTime.now().toString());
            messageProducer.sendImageAnalysisTask(analysisDTO);


        } catch (Exception e) {

            // 回滚操作：删除新上传的文件，恢复数据库记录
            if (videoUpdated) {
                cleanupCosFiles(articleId.toString());
                existingArticle.setVideoUrl(originalVideoUrl);
                existingArticle.setImages(originalImages);
                this.updateById(existingArticle);
            }
            throw new RuntimeException("视频更新失败", e);
        } finally {
            // 清理临时文件
            if (tempDir != null) {
                deleteDirectory(tempDir);
            }
        }
    }
}




